# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

[ -n "${gbmc_ncsi_br_deprecated_ips_lib-}" ] && return

source /usr/share/network/lib.sh || exit
source /usr/share/gbmc-net-lib.sh || exit

gbmc_ncsi_br_deprecated_ips_init=
declare -A gbmc_ncsi_br_deprecated_ips_confip=()
declare -A gbmc_ncsi_br_deprecated_ips_lastip=()
declare -A gbmc_ncsi_br_deprecated_ips_del=()
gbmc_ncsi_br_deprecated_ips_lastncsi=
gbmc_ncsi_br_deprecated_ips_confncsi=
declare -A gbmc_ncsi_br_deprecated_ips_savedconf=()

gbmc_ncsi_br_deprecated_ips_add_neighs() {
  local intf="$1"
  echo "(Re)adding neighbors for $intf" >&2

  local st=0
  sysctl net.ipv6.conf."$intf".proxy_ndp=1 >/dev/null || st=$?
  local ip
  for ip in "${!gbmc_ncsi_br_deprecated_ips_savedconf[@]}"; do
    [[ ${gbmc_ncsi_br_deprecated_ips_savedconf["$ip"]} != $intf ]] && continue
    ip -6 neigh replace proxy $ip dev $intf || st=$?
  done
  return $st
}

gbmc_ncsi_br_deprecated_ips_update() {
  local ip="$1"
  local intf="${gbmc_ncsi_br_deprecated_ips_lastip["$ip"]}"
  local intf_old="${gbmc_ncsi_br_deprecated_ips_confip["$ip"]-}"
  local del="${gbmc_ncsi_br_deprecated_ips_del["$ip"]-}"

  if [ "$intf_old" = "$intf" ]; then
    if [ "$intf" != '@NCSI_IF@' ] || [ "$gbmc_ncsi_br_deprecated_ips_confncsi" = "$gbmc_ncsi_br_deprecated_ips_lastncsi" ]; then
      return 0
    fi
  fi

  local act="add"
  if [ -n "$del" ]; then
    act="del"
  fi
  printf 'gBMC NCSI %s Deprecated Addrs to %s: %s\n' "$act" "$intf" "$ip" >&2

  # Calculate all of the potential neighbor addresses
  local pfx_bytes=()
  ip_to_bytes pfx_bytes "$ip"
  local pfx="$(ip_bytes_to_str pfx_bytes)"
  (( pfx_bytes[9] &= 0xf0 ))
  local stateless_pfx="$(ip_bytes_to_str pfx_bytes)"
  local stateless_ip=
  if [ -e /sys/class/net/gbmcbr ]; then
    local gbmcbr_mac="$(ip link show gbmcbr | tail -n 1 | awk '{print $2}')"
    local gbmcbr_eui48="$(mac_to_eui48 "$gbmcbr_mac")"
    stateless_ip="$(ip_pfx_concat "$stateless_pfx/80" "$gbmcbr_eui48")"
    stateless_ip="${stateless_ip%/*}"
  fi
  pfx_bytes[8]=0
  pfx_bytes[9]=0
  local host_pfx=
  if [ "$intf" = '@NCSI_IF@' -a -n "${gbmc_ncsi_br_deprecated_ips_lastncsi}" ]; then
    # Only impersonate the host if we have an NCSI state machine
    host_pfx="$(ip_bytes_to_str pfx_bytes)"
  fi

  # Determine a unique routing table number for the IP
  local rt="$(gbmc_net_route_table_for_intf "$intf")"

  local contents=
  read -r -d '' contents <<EOF
[Network]
IPv6ProxyNDP=yes
IPv6ProxyNDPAddress=$pfx
IPv6ProxyNDPAddress=$stateless_pfx
${host_pfx:+IPv6ProxyNDPAddress=}$host_pfx
${stateless_ip:+IPv6ProxyNDPAddress=}$stateless_ip
[RoutingPolicyRule]
To=$pfx/76
Table=main
Priority=$GBMC_INTF_ROUTE_TABLE_BASE
[RoutingPolicyRule]
From=$pfx/76
Table=$rt
Priority=$rt
EOF
  local file
  if [ -n "$intf_old" ]; then
    for file in /run/systemd/network/{00,}-bmc-"$intf_old".network.d/50-deprecated-"$ip".conf; do
      rm -f "$file"
    done
  fi
  for file in /run/systemd/network/{00,}-bmc-"$intf".network.d/50-deprecated-"$ip".conf; do
    mkdir -p -m 755 "$(dirname "$file")"
    if [ -n "$del" ]; then
      rm -f "$file"
    else
      printf '%s' "$contents" >"$file"
    fi
  done

  local st=0
  if [ -n "$intf_old" ]; then
    ip -6 neigh del proxy $pfx dev $intf_old 2>/dev/null || true
    ip -6 neigh del proxy $stateless_pfx dev $intf_old 2>/dev/null || true
    if [ -n "$host_pfx" ]; then
      ip -6 neigh del proxy $host_pfx dev $intf_old 2>/dev/null || true
    fi
    if [ -n "$stateless_ip" ]; then
      ip -6 neigh del proxy $stateless_ip dev $intf_old 2>/dev/null || true
    fi
    local rt_old="$(gbmc_net_route_table_for_intf "$intf_old")"
    ip -6 rule del from $pfx/76 lookup $rt_old 2>/dev/null || true
  fi
  ip -6 rule del to "$pfx/76" pref $GBMC_INTF_ROUTE_TABLE_BASE lookup main 2>/dev/null || true
  ip -6 rule del from "$pfx/76" pref $rt lookup $rt 2>/dev/null || true
  if [ -n "$del" ]; then
    unset 'gbmc_ncsi_br_deprecated_ips_savedconf["$pfx"]'
    ip -6 neigh del proxy $pfx dev $intf 2>/dev/null || true
    unset 'gbmc_ncsi_br_deprecated_ips_savedconf["$stateless_pfx"]'
    ip -6 neigh del proxy $stateless_pfx dev $intf 2>/dev/null || true
    if [ -n "$host_pfx" ]; then
      unset 'gbmc_ncsi_br_deprecated_ips_savedconf["$host_pfx"]'
      ip -6 neigh del proxy $host_pfx dev $intf 2>/dev/null || true
    fi
    if [ -n "$stateless_ip" ]; then
      unset 'gbmc_ncsi_br_deprecated_ips_savedconf["$stateless_ip"]'
      ip -6 neigh del proxy $stateless_ip dev $intf 2>/dev/null || true
    fi
  else
    ip -6 rule add to "$pfx/76" pref $GBMC_INTF_ROUTE_TABLE_BASE lookup main || st=$?
    ip -6 rule add from "$pfx/76" pref $rt lookup $rt || st=$?
    gbmc_ncsi_br_deprecated_ips_savedconf["$pfx"]="$intf"
    gbmc_ncsi_br_deprecated_ips_savedconf["$stateless_pfx"]="$intf"
    if [ -n "$host_pfx" ]; then
      gbmc_ncsi_br_deprecated_ips_savedconf["$host_pfx"]="$intf"
    fi
    if [ -n "$stateless_ip" ]; then
      gbmc_ncsi_br_deprecated_ips_savedconf["$stateless_ip"]="$intf"
    fi
    gbmc_ncsi_br_deprecated_ips_add_neighs "$intf" || st=$?
  fi
  if (( st != 0 )); then
    gbmc_net_networkd_reload $intf
  fi

  if [ -n "$del" ]; then
    unset 'gbmc_ncsi_br_deprecated_ips_lastip["$ip"]'
    unset 'gbmc_ncsi_br_deprecated_ips_confip["$ip"]'
  else
    gbmc_ncsi_br_deprecated_ips_confip["$ip"]="$intf"
  fi
  if [ "$intf" = '@NCSI_IF@' ]; then
    gbmc_ncsi_br_deprecated_ips_confncsi="$gbmc_ncsi_br_deprecated_ips_lastncsi"

    local nfcontents=
    read -r -d '' nfcontents <<EOF
table inet filter {
  chain ncsi_input {
    ip6 saddr != $pfx/76 ip6 daddr $pfx/76 jump ncsi_gbmc_br_pub_input
    ${host_pfx:+ip6 daddr $host_pfx/64 jump ncsi_legacy_input}
  }
  chain ncsi_forward {
    ip6 saddr != $pfx/76 ip6 daddr $pfx/76 accept
  }
}
EOF
    local rfile=/run/nftables/45-gbmc-ncsi-br-"$ip".rules
    mkdir -p -m 755 "$(dirname "$rfile")"
    if [ -n "$del" ]; then
      rm -f "$rfile"
    else
      printf '%s' "$nfcontents" >"$rfile"
    fi
    systemctl reset-failed nftables && systemctl --no-block reload-or-restart nftables || true
  fi
}

gbmc_ncsi_br_deprecated_ips_hook() {
  if [ "$change" = 'init' ]; then
    gbmc_ncsi_br_deprecated_ips_init=1
    gbmc_ip_monitor_defer
  elif [ "$change" = 'defer' -a -n "$gbmc_ncsi_br_deprecated_ips_init" ]; then
    local ip
    for ip in "${!gbmc_ncsi_br_deprecated_ips_lastip[@]}"; do
      gbmc_ncsi_br_deprecated_ips_update "$ip"
    done
  elif [ "$change" = 'addr' -a "$scope" = 'global' -a "$fam" = 'inet6' ] &&
      [ "$intf" = 'gbmcbr' -o "$intf" = '@NCSI_IF@' ] &&
      [[ "$flags" != *deprecated* ]]; then
    local pfx_bytes=()
    ip_to_bytes pfx_bytes "$ip" || return
    # No ULA Addresses
    if (( (pfx_bytes[0] & 0xfe) == 0xfc )); then
      return
    fi
    # We only want to allow a <pfx>::fd0x address, where x>0
    if (( pfx_bytes[8] != 0xfd || (pfx_bytes[9] & 0xf) == 0 )); then
      return
    fi
    for (( i = 10; i < 16; ++i )); do
      if (( pfx_bytes[i] != 0 )); then
        return
      fi
    done
    # Match the interface which has the address
    local matching_intf='@NCSI_IF@'
    local file
    for file in /run/ncsi-ips/*; do
      if [[ "$(<$file)" = "$ip" ]]; then
        matching_intf="${file##*/}"
        break
      fi
    done
    gbmc_ncsi_br_deprecated_ips_lastip["$ip"]="$matching_intf"
    if [ "$action" = 'add' ]; then
      unset 'gbmc_ncsi_br_deprecated_ips_del["$ip"]'
      gbmc_ip_monitor_defer
    fi
    if [ "$action" = 'del' ]; then
      gbmc_ncsi_br_deprecated_ips_del["$ip"]=1
      gbmc_ip_monitor_defer
    fi
  elif [ "$change" = 'link' -a "$action" = 'add' -a "$intf" = '@NCSI_IF@' ]; then
    if ip link show '@NCSI_IF@' | grep -q '^ *alias ncsi$'; then
      gbmc_ncsi_br_deprecated_ips_lastncsi=1
      gbmc_ip_monitor_defer
    else
      gbmc_ncsi_br_deprecated_ips_lastncsi=
      gbmc_ip_monitor_defer
    fi
    if [[ "$carrier" == 'UP' ]]; then
      gbmc_ncsi_br_deprecated_ips_add_neighs "$intf"
    fi
  elif [ "$change" = 'link' -a "$action" = 'add' -a "$carrier" = 'UP' ]; then
    if ip link show "$intf" | grep -q '^ *alias ncsi-usb$'; then
      gbmc_ncsi_br_deprecated_ips_add_neighs "$intf"
    fi
  fi
}

GBMC_IP_MONITOR_HOOKS+=(gbmc_ncsi_br_deprecated_ips_hook)

gbmc_ncsi_br_deprecated_ips_lib=1
